package edu.nf.ch06;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @Author gjh
 * @Date 2025/10/9
 * @Description:
 */
@Service
public class User {

    private static final String QUEUE_NAME = "code";
    private static ConnectionFactory connectionFactory;

    static {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        // 5672 是本机的端口号
        connectionFactory.setPort(5672);
    }

    public static String receive(){
        final StringBuilder result = new StringBuilder();
        try {
            // 1. 建立连接和通道
            Connection conn = connectionFactory.newConnection();
            Channel channel = conn.createChannel();

            // 2. 确保队列存在
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            // 3. 创建消息回调处理器
            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("接收到消息：" + message);
                result.append(message);
            };

            // 4. 监听队列（自动确认）
            channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});

            // 5. 简单等待接收（演示用，实际中建议用 CountDownLatch 或持续监听）
            Thread.sleep(1000);

            // 6. 关闭资源
            channel.close();
            conn.close();

            return result.toString();
        } catch (Exception e) {
            throw new RuntimeException("操作失败：" + e.getMessage(), e);
        }
    }
}
